from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import RetrieveModelMixin, ListModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreaSerializer, SubAreaSerializer


# Create your views here.
# 请求方式： GET /areas/
# class AreasView(GenericAPIView):
#     """
#     获取省级
#     """
#     queryset = Area.objects.filter(parent=None)
#     serializer_class = AreaSerializer
#
#     def get(self, request):
#         areas = self.get_queryset()
#         s = self.get_serializer(instance=areas, many=True)
#         # return Response(s.data)


# class AreaView(GenericAPIView):
#     """
#     获取市级地区
#     """
#     queryset = Area.objects.all()
#     serializer_class = SubAreaSerializer
#
#     def get(self, request, pk):
#         area = self.get_object()
#         s = self.get_serializer(area)
#         return Response(s.data)

#
# class AreasView(ListModelMixin, GenericViewSet):
#     def get_queryset(self):
#         if self.action == 'list':
#             return Area.objects.filter(parent=None)
#         else:
#             return Area.objects.all()
#
#     def get_serializer_class(self):
#         if self.action == 'list':
#             return AreaSerializer
#         else:
#             return SubAreaSerializer
#
#     def list(self, request):
#         areas = self.get_queryset()
#         serializer = self.get_serializer(instance=areas, many=True)
#         return Response(serializer.data)
#
#     def retrieve(self, request, pk):
#         area = self.get_object()
#         serializer = self.get_serializer(instance=area)
#
#         return Response(serializer.data)


class AreasViewSet(CacheResponseMixin, ReadOnlyModelViewSet ):
    """
    行政区划信息
    """
    pagination_class = None

    def get_queryset(self):
        """
        提供查询集
        :return:
        """
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

    def get_serializer_class(self):
        """
        提供不同序列化器
        :return:
        """
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubAreaSerializer
